package com.yeyaomai.dksns.flowis.servlet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.yeyaomai.dksns.flowis.util.VelocityToolDateUtils;
import com.yeyaomai.dksns.flowis.domain.ReferCategory;
import com.yeyaomai.dksns.flowis.domain.ReferDomain;
import com.yeyaomai.dksns.flowis.domain.ReferPage;
import com.yeyaomai.dksns.flowis.service.DownExcelService;
import com.yeyaomai.dksns.flowis.service.ReferCategoryService;
import com.yeyaomai.dksns.flowis.service.ReferDomainService;
import com.yeyaomai.dksns.flowis.service.ReferPageService;
import com.yeyaomai.dksns.flowis.service.result.DynamicXml;
import com.yeyaomai.dksns.flowis.util.Globals;

@Controller
@RequestMapping("/domain/*")
public class RefererController {

	@Autowired
	private ReferDomainService referDomainService;

	@Autowired
	private ReferPageService referPageService;

	@Autowired
	private ReferCategoryService referCategoryService;
	
	@Autowired
	private DownExcelService downExcelService;

	@RequestMapping(value = "/arrive")
	public ModelAndView getTodayCount(HttpServletRequest request)
			throws ParseException {
		Map<String, Object> map = new HashMap<String, Object>();
		String formDate = request.getParameter("formDate");
		String toDate = request.getParameter("toDate");
		String number = request.getParameter("number");
        String type = request.getParameter("type");
		String date = formDate;
		map.put("dateCount", 2);
		ModelAndView view = new ModelAndView("from-domain");
		view.addObject("formDate", formDate);
		view.addObject("toDate", toDate);
		view.addObject("type",type);
		view.addObject("nowDate", Globals.FORMAT_TYPE_A.format(new Date()));
		view.addObject("month", VelocityToolDateUtils.getDay(Integer.valueOf("-"+Globals.FORMAT_TYPE_D.format(new Date()))+1));
		if (formDate.equals(toDate)) {
			map.put("dateCount", 1);
		}
		toDate = Globals.FORMAT_TYPE_A.format(Globals.FORMAT_TYPE_A.parse(
				toDate).getTime()
				+ 1 * 24 * 3600 * 1000);

		map.put("fromReferDay", date);
		map.put("toReferDay", toDate);
		Page<ReferDomain> result = referDomainService.getDataPage(map,
				Integer.valueOf(number));
		view.addObject("result", result);
		view.addObject("number", number);
		return view;
	}

	/**
	 * 拼写饼状图
	 * 
	 * @param fromDate
	 * @param toDate
	 * @param response
	 * @throws IOException
	 * @throws ParseException
	 */
	@RequestMapping(value = "/piexml")
	public void changeXml(@RequestParam("fromDate") String fromDate,
			@RequestParam("toDate") String toDate, HttpServletResponse response)
			throws IOException, ParseException {
		Map<String, String> referDomain = new HashMap<String, String>();
		Map<String, Object> map = new HashMap<String, Object>();
		List<ReferDomain> domain = new ArrayList<ReferDomain>();
		map.put("dateCount", 2);
		String date = Globals.FORMAT_TYPE_A.format(Globals.FORMAT_TYPE_A.parse(
				toDate).getTime()
				+ 1 * 24 * 3600 * 1000);
		if (fromDate.equals(toDate)) {
			map.put("dateCount", 1);
		}
		map.put("fromReferDay", fromDate);
		map.put("toReferDay", date);
		map.put("startNumber", null);
		map.put("endNumber", null);
		domain = referDomainService.getReferDomainByDay(map);
		Integer othernumber = 0;
		for (int i = 0; i < domain.size(); i++) {
			ReferDomain referdomain = domain.get(i);
			if (i >= 5) {
				othernumber += referdomain.getVisitCount();
			} else {
				referDomain.put(referdomain.getDomainName(), referdomain
						.getVisitCount().toString());
			}
		}
		referDomain.put("其他", othernumber.toString());
		String xml = DynamicXml.getpie(referDomain, fromDate, toDate);
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().print(xml);
	}

	@RequestMapping(value = "/referPage")
	public ModelAndView getTodayPage(HttpServletRequest request)
			throws ParseException {
		Map<String, Object> map = new HashMap<String, Object>();
		String formDate = request.getParameter("formDate");
		String toDate = request.getParameter("toDate");
		String number = request.getParameter("number");
		String type = request.getParameter("type");
		String date = formDate;
		map.put("dateCount", 2);
		ModelAndView view = new ModelAndView("from-page");
		view.addObject("formDate", formDate);
		view.addObject("toDate", toDate);
		view.addObject("type",type);
		view.addObject("month", VelocityToolDateUtils.getDay(Integer.valueOf("-"+Globals.FORMAT_TYPE_D.format(new Date()))+1));
		view.addObject("nowDate", Globals.FORMAT_TYPE_A.format(new Date()));
		if (formDate.equals(toDate)) {
			map.put("dateCount", 1);
		}
		toDate = Globals.FORMAT_TYPE_A.format(Globals.FORMAT_TYPE_A.parse(
				toDate).getTime()
				+ 1 * 24 * 3600 * 1000);

		map.put("fromReferDay", date);
		map.put("toReferDay", toDate);
		Page<ReferPage> result = referPageService.getDataPage(map,
				Integer.valueOf(number));
		view.addObject("result", result);
		view.addObject("number", number);
		return view;
	}

	@RequestMapping(value = "/category")
	public ModelAndView getTodayCategory(HttpServletRequest request)
			throws ParseException {
		Map<String, Object> map = new HashMap<String, Object>();
		String formDate = request.getParameter("formDate");
		String toDate = request.getParameter("toDate");
		String type = request.getParameter("type");
		String date = formDate;
		map.put("dateCount", 2);
		ModelAndView view = new ModelAndView("from-category");
		view.addObject("formDate", formDate);
		view.addObject("toDate", toDate);
		view.addObject("type",type);
		view.addObject("month", VelocityToolDateUtils.getDay(Integer.valueOf("-"+Globals.FORMAT_TYPE_D.format(new Date()))+1));
		view.addObject("nowDate", Globals.FORMAT_TYPE_A.format(new Date()));
		if (formDate.equals(toDate)) {
			map.put("dateCount", 1);
		}
		toDate = Globals.FORMAT_TYPE_A.format(Globals.FORMAT_TYPE_A.parse(
				toDate).getTime()
				+ 1 * 24 * 3600 * 1000);

		map.put("fromReferDay", date);
		map.put("toReferDay", toDate);
		List<ReferCategory> category = referCategoryService
				.getReferCategoryByDay(map);
		long engineCount = 0;
		long externalCount = 0;
		long directCount = 0;
		for (int i = 0; i < category.size(); i++) {
			engineCount += category.get(i).getEngineCount();
			externalCount += category.get(i).getExternalCount();
			directCount += category.get(i).getDirectCount();
		}
		long totalCount = engineCount + externalCount + directCount;
		String enginePercent = String.format("%.2f", (double) engineCount
				/ totalCount * 100);
		String externalPercent = String.format("%.2f", (double) externalCount
				/ totalCount * 100);
		String directPercent = String.format("%.2f", (double) directCount
				/ totalCount * 100);
		if(enginePercent.equals("NaN") || enginePercent.equals("Infinity"))
		{
			enginePercent ="0.00";
		}
		if(externalPercent.equals("NaN") || externalPercent.equals("Infinity"))
		{
			externalPercent ="0.00";
		}
		if(directPercent.equals("NaN") || directPercent.equals("Infinity"))
		{
			directPercent ="0.00";
		}
		view.addObject("engineCount", engineCount);
		view.addObject("externalCount", externalCount);
		view.addObject("directCount", directCount);
		view.addObject("enginePercent", enginePercent);
		view.addObject("externalPercent", externalPercent);
		view.addObject("directPercent", directPercent);
		view.addObject("category", category);
		return view;
	}

	@RequestMapping(value = "/changelinexmlByDomain")
	public void changeLineXml(@RequestParam("formDate") String formDate,
			@RequestParam("keyid") String keyid,
			@RequestParam("toDate") String toDate, HttpServletResponse response)
			throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("dateCount", 2);
		if (formDate.equals(toDate)) {
			map.put("dateCount", 1);
		}
		String date = Globals.FORMAT_TYPE_A.format(Globals.FORMAT_TYPE_A.parse(
				toDate).getTime()
				+ 1 * 24 * 3600 * 1000);
		map.put("fromReferDay", formDate);
		map.put("toReferDay", date);
		// 处理今天数据的到时候改成动态，现在没有值。
		List<ReferCategory> category = referCategoryService
				.getReferCategoryByDay(map);
		String xml = DynamicXml.getLineByDomain(category, keyid, formDate,
				toDate);
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().print(xml);
	}

	/**
	 * 来路域名历史数据展示
	 * @param request
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value = "/history")
	public ModelAndView getReferDomainByDomain(HttpServletRequest request)
			throws ParseException {
		String domainName = request.getParameter("domainName");
		String toDate = request.getParameter("date");
		Date date = Globals.FORMAT_TYPE_A.parse(toDate);
		Date d = null;
		String type = request.getParameter("type");
		String fromDate = "";
		if(type.equals("-1"))
		{
			d = DateUtils
					.truncate(DateUtils.addDays(date, -30), Calendar.DATE);
			fromDate = Globals.FORMAT_TYPE_A.format(d);
		}
		else if(type.equals("1"))
		{
			d = DateUtils
					.truncate(DateUtils.addDays(date, 30), Calendar.DATE);
			String middle = toDate;
			toDate = Globals.FORMAT_TYPE_A.format(d);
			fromDate = middle;
		}
		String currentTime = Globals.FORMAT_TYPE_A.format(new Date());
		ModelAndView view = new ModelAndView("domain-history");

		if((Globals.FORMAT_TYPE_A.parse(toDate).getTime()) >= (Globals.FORMAT_TYPE_A.parse(currentTime).getTime()))
		{
			view.addObject("show", 1);
		}
		else
		{
			view.addObject("show", 0);
		}
		view.addObject("domainName", domainName);
		view.addObject("currentDate",currentTime );
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("domainName", domainName);
		map.put("fromDate", fromDate);
		map.put("toDate", toDate);
		List<ReferDomain> domainList = new ArrayList<ReferDomain>();
		domainList = referDomainService.getReferDomainByDomain(map);
		view.addObject("domainList", domainList);
		view.addObject("fromDate", fromDate);
		view.addObject("toDate", toDate);
		return view;
	}

	/**
	 * 来路域名柱状图展示
	 * @param fromDate 开始时间
	 * @param value 类型
	 * @param toDate 结束时间
	 * @param domainName 来路域名
	 * @param response 返回拼装数据
	 * @throws IOException
	 * @throws ParseException
	 */
	@RequestMapping(value = "/historyxml")
	public void changeHistoryXml(@RequestParam("fromDate") String fromDate,
			@RequestParam("value") String value,
			@RequestParam("toDate") String toDate, @RequestParam("domainName") String domainName,HttpServletResponse response) throws IOException, ParseException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("domainName", domainName);
		map.put("fromDate", fromDate);
		map.put("toDate", toDate);

		List<ReferDomain> domainList = referDomainService
				.getReferDomainByDomain(map);
		String xml = DynamicXml.getColumnByDomain(domainList, value, fromDate,toDate);

		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().print(xml);
	}
	
	/**
	 * 来路页面历史数据展示
	 * @param request
	 * @return
	 * @throws ParseException
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value = "/pagehistory")
	public ModelAndView getReferPageByPageName(HttpServletRequest request)
			throws ParseException, UnsupportedEncodingException {
		String pageName = request.getParameter("pageName");
		String toDate = request.getParameter("date");
		Date date = Globals.FORMAT_TYPE_A.parse(toDate);
		Date d = null;
		String type = request.getParameter("type");
		String fromDate = "";
		if(type.equals("-1"))
		{
			d = DateUtils
					.truncate(DateUtils.addDays(date, -30), Calendar.DATE);
			fromDate = Globals.FORMAT_TYPE_A.format(d);
		}
		else if(type.equals("1"))
		{
			d = DateUtils
					.truncate(DateUtils.addDays(date, 30), Calendar.DATE);
			String middle = toDate;
			toDate = Globals.FORMAT_TYPE_A.format(d);
			fromDate = middle;
		}
		String currentTime = Globals.FORMAT_TYPE_A.format(new Date());
		ModelAndView view = new ModelAndView("page-history");

		if((Globals.FORMAT_TYPE_A.parse(toDate).getTime()) >= (Globals.FORMAT_TYPE_A.parse(currentTime).getTime()))
		{
			view.addObject("show", 1);
		}
		else
		{
			view.addObject("show", 0);
		}
		view.addObject("pageName", pageName);
		view.addObject("currentDate",currentTime );
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("pageName", pageName);
		map.put("fromDate", fromDate);
		map.put("toDate", toDate);
		List<ReferPage> pageList = new ArrayList<ReferPage>();
		pageList = referPageService.getReferPageByPageName(map);
		view.addObject("pageList", pageList);
		view.addObject("fromDate", fromDate);
		view.addObject("toDate", toDate);
		return view;
	}

	
	/**
	 * 来路页面柱状图展示
	 * @param fromDate 开始时间
	 * @param value 类型
	 * @param toDate 结束时间
	 * @param pageName 来路页面
	 * @param response 返回拼装数据
	 * @throws IOException
	 * @throws ParseException
	 */
	@RequestMapping(value = "/pagexml")
	public void changePageHistoryXml(@RequestParam("fromDate") String fromDate,
			@RequestParam("value") String value,
			@RequestParam("toDate") String toDate, @RequestParam("pageName") String pageName,HttpServletResponse response) throws IOException, ParseException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("pageName", pageName);
		map.put("fromDate", fromDate);
		map.put("toDate", toDate);

		List<ReferPage> pageList = referPageService.getReferPageByPageName(map);
				
		String xml = DynamicXml.getColumnByPage(pageList, value, fromDate,toDate);

		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().print(xml);
	}
	
	/**
	 * 来路分类历史数据展示
	 * @param request
	 * @return
	 * @throws ParseException
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value = "/categoryhistory")
	public ModelAndView getReferCategoryByDay(HttpServletRequest request)
			throws ParseException, UnsupportedEncodingException {
		String toDate = request.getParameter("date");
		Date date = Globals.FORMAT_TYPE_A.parse(toDate);
		Date d = null;
		String type = request.getParameter("type");
		String fromDate = "";
		if(type.equals("-1"))
		{
			d = DateUtils
					.truncate(DateUtils.addDays(date, -30), Calendar.DATE);
			fromDate = Globals.FORMAT_TYPE_A.format(d);
		}
		else if(type.equals("1"))
		{
			d = DateUtils
					.truncate(DateUtils.addDays(date, 30), Calendar.DATE);
			String middle = toDate;
			toDate = Globals.FORMAT_TYPE_A.format(d);
			fromDate = middle;
		}
		String currentTime = Globals.FORMAT_TYPE_A.format(new Date());
		ModelAndView view = new ModelAndView("category-history");

		if((Globals.FORMAT_TYPE_A.parse(toDate).getTime()) >= (Globals.FORMAT_TYPE_A.parse(currentTime).getTime()))
		{
			view.addObject("show", 1);
		}
		else
		{
			view.addObject("show", 0);
		}
		view.addObject("currentDate",currentTime );
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("fromReferDay", fromDate);
		map.put("toReferDay", toDate);
		map.put("dateCount", 2);
		List<ReferCategory> categoryList = new ArrayList<ReferCategory>();
		categoryList = referCategoryService.getReferCategoryByDay(map);
		view.addObject("categoryList", categoryList);
		view.addObject("fromDate", fromDate);
		view.addObject("toDate", toDate);
		return view;
	}
	
	/**
	 * 来路页面柱状图展示
	 * @param fromDate 开始时间
	 * @param value 类型
	 * @param toDate 结束时间
	 * @param pageName 来路页面
	 * @param response 返回拼装数据
	 * @throws IOException
	 * @throws ParseException
	 */
	@RequestMapping(value = "/categoryxml")
	public void changeCategoryHistoryXml(@RequestParam("fromDate") String fromDate,
			@RequestParam("value") String value,
			@RequestParam("toDate") String toDate,HttpServletResponse response) throws IOException, ParseException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("fromReferDay", fromDate);
		map.put("toReferDay", toDate);
		map.put("dateCount", 2);
		List<ReferCategory> categoryList = referCategoryService.getReferCategoryByDay(map);
				
		String xml = DynamicXml.getColumnByCategory(categoryList, value, fromDate,toDate);

		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().print(xml);
	}
	
	
	 //来源分析报表下载
		@RequestMapping(value="down")
		public void download(HttpServletRequest request,HttpServletResponse response) throws ParseException, IOException {
			
			String startTime = request.getParameter("startTime");
			String endTime = request.getParameter("endTime");
			endTime = Globals.FORMAT_TYPE_A.format(Globals.FORMAT_TYPE_A.parse(endTime).getTime()+ 1 * 24 * 3600 * 1000);
			String type = request.getParameter("type");
			List<String>  heads  =new ArrayList<String>();
			List<String> pros =new ArrayList<String>();
			String title ="";
			if(type.equals("1"))
			{
				title = "来路域名("+startTime+"至"+endTime+")";
				String newTitle = URLEncoder.encode(title, "UTF-8"); 
				heads.add("时间");
			    heads.add("来路域名");
			    heads.add("访问次数");
			    heads.add("独立访客");
			    heads.add("IP数");
			    heads.add("新独立访客");
			    heads.add("新独立访客次数");
			    heads.add("站内总浏览次数");
			    
			    pros.add("referDate");
			    pros.add("domainName");
			    pros.add("visitCount");
			    pros.add("uniqueHost");
			    pros.add("ip");
			    pros.add("newUniqueHost");
			    pros.add("newUniqueHostCount");
			    pros.add("standCount");
			    Map<String,Object> map = new HashMap<String, Object>();
			    map.put("fromReferDay", startTime);
				map.put("toReferDay", endTime);
				map.put("dateCount", 1);
				map.put("startNumber", null);
				map.put("endNumber", null);
			    List<ReferDomain> domainList=referDomainService.getReferDomainByDay(map);
			    response.setContentType("application/vnd.ms-excel");
			    response.setHeader("Content-disposition", "attachment;filename=" + newTitle+".xls");   
			    downExcelService.exportExcel(title, heads, domainList, response.getOutputStream(), pros);
			}
			else if(type.equals("2"))
			{
				title = "来路页面("+startTime+"至"+endTime+")";
				String newTitle = URLEncoder.encode(title, "UTF-8"); 
				heads.add("时间");
			    heads.add("来路页面");
			    heads.add("访问次数");
			    heads.add("独立访客");
			    heads.add("IP数");
			    heads.add("新独立访客");
			    heads.add("新独立访客次数");
			    heads.add("站内总浏览次数");
			  
			    pros.add("date");
			    pros.add("pageName");
			    pros.add("visitCount");
			    pros.add("uniqueHost");
			    pros.add("ip");
			    pros.add("newUniqueHost");
			    pros.add("newUniqueHostCount");
			    pros.add("standCount");
			    Map<String,Object> map = new HashMap<String, Object>();
			    map.put("fromReferDay", startTime);
				map.put("toReferDay", endTime);
				map.put("dateCount", 1);
				map.put("startNumber", null);
				map.put("endNumber", null);
			    List<ReferPage> pageList = referPageService.getReferPageByDay(map);
			    response.setContentType("application/vnd.ms-excel");
			    response.setHeader("Content-disposition", "attachment;filename=" + newTitle+".xls");   
			    downExcelService.exportExcel(title, heads, pageList, response.getOutputStream(), pros);
			}
			else if(type.equals("3"))
			{
				title = "来路分类("+startTime+"至"+endTime+")";
				String newTitle = URLEncoder.encode(title, "UTF-8"); 
				heads.add("时间");
			    heads.add("小时");
			    heads.add("搜索引擎访问次数");
			    heads.add("外部链接访问次数");
			    heads.add("直接访问次数");
			    
			    pros.add("referDate");
			    pros.add("hour");
			    pros.add("engineCount");
			    pros.add("externalCount");
			    pros.add("directCount");

			    Map<String,Object> map = new HashMap<String, Object>();
			    map.put("fromReferDay", startTime);
				map.put("toReferDay", endTime);
				map.put("dateCount", 1);
				map.put("startNumber", null);
				map.put("endNumber", null);
			    List<ReferCategory> categoryList = referCategoryService.getReferCategoryByDay(map);
			    response.setContentType("application/vnd.ms-excel");
			    response.setHeader("Content-disposition", "attachment;filename=" + newTitle+".xls");   
			    downExcelService.exportExcel(title, heads, categoryList, response.getOutputStream(), pros);
			}
		}
}
